package cn.touna.jss.modules.custom.blacklist;

import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.credit.entity.CreditRecordBlackEnity;
import cn.touna.jss.modules.credit.mapper.CreditRecordBlackEnityMapper;
import cn.touna.jss.modules.custom.blacklist.entity.BlackListRequest;
import cn.touna.jss.modules.third.baidu.BaiDuService;
import cn.touna.jss.modules.third.baidu.entity.BaiduRequestEntity;
import cn.touna.jss.modules.third.zzc.ZhongzhichengService;
import cn.touna.jss.modules.third.zzc.entity.ZhongzhichengRequestEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 黑名单
 * Created by Steve.Tao on 2017/8/23.
 */
@Service
public class BlackListService {

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    private BaiDuService baiDuService;

    @Autowired
    private ZhongzhichengService zhongzhichengService;

    @Autowired
    CreditRecordBlackEnityMapper blackMapper;

    private List<String> zzcCodes = Arrays.asList("F11", "F12", "F13", "F14", "F21", "F22", "F23", "F30", "F31", "F40", "P10", "P20", "P30");

    @ApiMapping(value="blackList.getBlackList", desc="复合接口.黑名单查询（百度/中智诚）")
    public Response getBlackList(BlackListRequest.GetBlackListRequest request) {

        Response response = ValidUtil.valid(request);
        if (response != null)
            return response;

        BaiduRequestEntity baiduRequestEntity = new BaiduRequestEntity();
        baiduRequestEntity.setRequestId(TracerContextUtil.getTraceId());
        baiduRequestEntity.setName(request.getName());
        baiduRequestEntity.setIdCard(request.getIdCard());
        baiduRequestEntity.setMobile(request.getMobile());
        Response baiduRes = null;
        try {
            baiduRes = baiDuService.getBlackList(baiduRequestEntity);
        } catch (Exception e) {
            logger.error(e);
        }

        ZhongzhichengRequestEntity zzcRequestEntity = new ZhongzhichengRequestEntity();
        zzcRequestEntity.setIdCard(request.getIdCard());
        zzcRequestEntity.setName(request.getName());
        zzcRequestEntity.setMobile(request.getMobile());
        Response zzcRes = null;
        try {
            zzcRes = zhongzhichengService.getBlackList(zzcRequestEntity);
        } catch (Exception e) {
            logger.error(e);
        }

        boolean baiduSuccess = baiduRes != null && baiduRes.checkIfSuccess();
        boolean zzcSuccess = zzcRes != null && zzcRes.checkIfSuccess();

        if (baiduSuccess || zzcSuccess) {
        } else {
            return new Response().fail(SystemErrorCodeEnum.CRS_NO_DATA_FOUND);
        }

        //组装黑名单数据
        JSONArray blackReasonArray = new JSONArray();
        if (baiduSuccess) {
            try {
                JSONObject jRes = JSON.parseObject(baiduRes.getData() + "");
                String retCode = jRes.getString("retCode");
                if ("0".equals(retCode)) {
                    JSONObject resultObj = jRes.getJSONObject("result");
                    String blackLevel = resultObj.getString("blackLevel");
                    if (!StringUtils.isEmpty(blackLevel) && !"-9999".equals(blackLevel)) {
                        String blackReason = resultObj.getString("blackReason");
                        String[] arr = blackReason.split(":");
                        for (String str : arr) {
                            JSONObject obj = new JSONObject();
                            obj.put("type", "S001");
                            obj.put("blackReason", str);
                            obj.put("blackLevel", blackLevel);
                            blackReasonArray.add(obj);
                        }
                    }
                } else {
                    logger.info("请求百度黑名单成功，返回结果状态为不再成功，结果为{}", jRes);
                }
            } catch (Exception e) {
                logger.error("请求百度黑名单异常：{}", e);
            }
        }

        if (zzcSuccess) {
            try {
                JSONObject jRes = JSON.parseObject(zzcRes.getData() + "");
                JSONArray records = jRes.getJSONArray("records");
                for (int i = 0; i < records.size(); i++) {
                    JSONObject _record = records.getJSONObject(i);
                    JSONObject obj = new JSONObject();
                    obj.put("type", "S002");
                    String confirmDetails = "";
                    if (_record.containsKey("confirm_details")) {
                        confirmDetails = _record.getString("confirm_details");
                    }
                    if (!StringUtils.isEmpty(confirmDetails) && !zzcCodes.contains(confirmDetails)) {
                        confirmDetails = "0";
                    }
                    obj.put("blackReason", confirmDetails);
                    blackReasonArray.add(obj);
                }
            } catch (Exception e) {
                logger.error("请求中智诚黑名单异常：{}", e);
            }
        }

        saveBlack(baiduRequestEntity,blackReasonArray);
        return ResponseFactory.success(blackReasonArray);
    }

    private void saveBlack(BaiduRequestEntity baiduRequestEntity, JSONArray blackReasonArray) {
        logger.info("sync saveBlack reqEntiy:{} blackReason:{}", baiduRequestEntity, blackReasonArray);
        for (int i = 0; i < blackReasonArray.size(); i++) {
            JSONObject jsonObject = (JSONObject) blackReasonArray.get(i);
            String blackReason = jsonObject.getString("blackReason");
            if (!StringUtils.isEmpty(blackReason)) {
                CreditRecordBlackEnity blackEnity = new CreditRecordBlackEnity();
                blackEnity.setIdNo(baiduRequestEntity.getIdCard());
                blackEnity.setCrNo(blackEnity.getCrNo());
                blackEnity.setMobile(blackEnity.getMobile());
                blackEnity.setBlackreason(blackReason);
                blackEnity.setType(jsonObject.getString("type"));
                blackMapper.insert(blackEnity);
            }
        }
    }


}
